$(function() {
  //新建文章按钮
  var ul = $(".sidebar-box ul");
  var essayId = fi.getParameter2(1);
  if (essayId) {
    ul
      .find("a[href='/editor/" + essayId + "']")
      .parent()
      .addClass("active");

    var editor = new Simditor({
      textarea: $("#editor"),
      upload: {
        url: "/upload-image",
        params: null,
        leaveConfirm: "正在上传文件",
        connectionCount: 3
      }
    });

    //保存文章
    $("#btn-save").on("click", function(e) {
      //阻止默认事件,防止自动提交表单
      e.preventDefault();
      var essayId = $("#essay-id").val();
      var title = $("#essay-title").val();
      var content = $(".simditor-body").html();
      var cate=$(".essay-cate").val();
      var abstract = $(".simditor-body")
        .text()
        .slice(0, 200);

      $.ajax({
        url: "/editor/update-essay",
        method: "post",
        data: {
          cate:cate,
          essayId: essayId,
          title: title,
          content: content,
          abstract: abstract
        },
        success: function(data) {
          if (data.code == 0) {
            var a = $("a[href='/editor/" + essayId + "']");
            a.text(title);
          }
        }
      });
    });
  }

  $(".btn-add").on("click", function(e) {
    e.preventDefault();
    $.ajax({
      url: "/editor/add-essay",
      method: "post",
      success: function(data) {
        if (data.code == 0) {
          console.log(ul);
          ul.prepend(data.html);
        }
      }
    });
  });

  //删除文章的按钮
  $(".btn-del").on("click", function(e) {
    var jThis = $(this);
    var a = jThis.prev("a");
    var href = a.attr("href");
    var essayId = href.slice(8);
    console.log(essayId);
    $.ajax({
      url: "/editor/del-essay",
      method: "post",
      data: {
        essayId: essayId
      },
      success: function(data) {
        if(data.code==0){
          location.href="/editor";
        }
      }
    });
  });
});
